/**
 * Copyright (C) 2012 The SkyTvOS Project
 * <p/>
 * Version     Date           Author
 * ─────────────────────────────────────
 * 2014-6-11         luwei
 */

package com.coocaa.x.framework.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.data.JObject;
import com.skyworth.framework.skysdk.ipc.SkyStartActivity;
import com.skyworth.framework.skysdk.logger.SkyLogger;
import com.skyworth.framework.skysdk.logger.SkyServerLogger;
import com.umeng.analytics.MobclickAgent;

import java.util.HashMap;
import java.util.Map;

public class LogUtils {
    static {
        //因为有View，要禁掉普通Activity的提交方式
        MobclickAgent.openActivityDurationTrack(false);
        //设置更新策略可由后台管理系统配置
        MobclickAgent.updateOnlineConfig(CoocaaApplication.getContext());
        SkyLogger.d("UMENG", "device_info:" + getDeviceInfo(CoocaaApplication.getContext()));
    }

    private static String getDeviceInfo(Context context) {
        try {
            org.json.JSONObject json = new org.json.JSONObject();
            android.telephony.TelephonyManager tm = (android.telephony.TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE);

            String device_id = tm.getDeviceId();

            android.net.wifi.WifiManager wifi = (android.net.wifi.WifiManager) context.getSystemService(Context.WIFI_SERVICE);

            String mac = wifi.getConnectionInfo().getMacAddress();
            json.put("mac", mac);

            if (TextUtils.isEmpty(device_id)) {
                device_id = mac;
            }

            if (TextUtils.isEmpty(device_id)) {
                device_id = android.provider.Settings.Secure.getString(context.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
            }

            json.put("device_id", device_id);

            return json.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static final String TAG = "superx";

    public static String throwable2String(Throwable t) {
        String ret = t.toString() + "\n";
        StackTraceElement[] es = t.getStackTrace();
        for (StackTraceElement e : es) {
            String file_line = "    " + e.getClassName() + "." + e.getMethodName() + "("
                    + e.getFileName() + "@" + e.getLineNumber() + ")";
            ret += file_line + "\n";
        }
        return ret;
    }

    public static void throwable(Throwable t) {
    }

    private static String processName = null;

    private synchronized static String m(String msg) {
        if (processName == null) {
            int pid = android.os.Process.myPid();
            ActivityManager mActivityManager = (ActivityManager) CoocaaApplication.getContext()
                    .getSystemService(Context.ACTIVITY_SERVICE);
            for (ActivityManager.RunningAppProcessInfo appProcess : mActivityManager
                    .getRunningAppProcesses()) {
                if (appProcess.pid == pid) {
                    processName = appProcess.processName;
                    break;
                }
            }
        }
        return "<<" + processName + ">>[" + msg + "]";
    }

    public static void d(String msg) {
        d(TAG, msg);
    }

    public static void d(String tag, String msg) {
//        LogUtils.d(tag, m(msg));
        SkyLogger.d(tag, m(msg));
    }

    public static void e(String msg) {
        e(TAG, msg);
    }

    public static void e(String tag, String msg) {
//        LogUtils.e(tag, m(msg));
        SkyLogger.e(tag, m(msg));
    }

    public static void i(String msg) {
        i(TAG, msg);
    }

    public static void i(String tag, String msg) {
//        LogUtils.i(tag, m(msg));
        SkyLogger.i(tag, m(msg));
    }

    public static void v(String msg) {
        v(TAG, msg);
    }

    public static void v(String tag, String msg) {
//        LogUtils.v(tag, m(msg));
        SkyLogger.v(tag, m(msg));
    }

    public static class SubmitLog extends JObject {
        public String productID;
        public String id = null;
        public Map<String, String> params = new HashMap<String, String>();

        public SubmitLog() {

        }

        public SubmitLog(String productID, String id) {
            this.productID = productID;
            this.id = id;
        }

        public synchronized void addParam(String key, String value) {
            params.put(key, value);
        }

        public synchronized void removeParam(String key) {
            params.remove(key);
        }
    }

    public static final String PRODUCTID_APPSTORE = "AppStore";
    public static final String PRODUCTID_HALL = "OperationHall";

    public static void submit(SubmitLog log) {
        submit(log.productID, log.id, log.params);
    }

    public static void submit(String productID, String id, Map<String, String> params) {
        try {
            SkyServerLogger.submitAppLog(CoocaaApplication.getContext(), productID, SkyServerLogger.LOGTYPE.Action,
                    id, 0, params, false);
            MobclickAgent.onEvent(CoocaaApplication.getContext(), id, params);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void onViewPageStart(Context context, String pageName, Map<String, String> pageDetail) {
        try {
            SkyStartActivity.onViewPageOpen(context, pageName, pageDetail);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void onViewPageEnd(Context context, String pageName, Map<String, String> pageDetail) {
        try {
            SkyStartActivity.onViewPageClose(context, pageName, pageDetail);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void onPageStart(Activity activity, String pageName) {
        try {
            MobclickAgent.onPageStart(pageName);
            SkyStartActivity.onCreate(activity);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void onPageResume(Activity activity, Map<String, String> params) {
        try {
            MobclickAgent.onResume(CoocaaApplication.getContext());
            SkyStartActivity.onPageOpen(activity, params);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void onPagePause(Activity activity) {
        MobclickAgent.onPause(CoocaaApplication.getContext());
        SkyStartActivity.onPageClose(activity);
    }

    public static void onPageEnd(Activity activity, String pageName) {
        try {
            MobclickAgent.onPageEnd(pageName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
